#include "abstract-database-client.h"
#include "double-spin-box-delegate.h"
#include "line-edit-delegate.h"
#include "model-result.h"
#include "product-in-warehouse-section-model.h"
#include "product-in-warehouse-section-queries.h"
#include "spin-box-delegate.h"
#include "value-result.h"

ProductInWarehouseSectionModel::ProductInWarehouseSectionModel(QObject *parent) :
    ProductSectionModel(parent)
{
}

void ProductInWarehouseSectionModel::setupQueries()
{
    m_queries = new ProductInWarehouseSectionQueries(this);
}

void ProductInWarehouseSectionModel::loadData()
{
    ModelResult* result = m_databaseClient->selectModel(m_queries->selectQuery(0, 0), m_loadingParameters);
    connect (result, &ModelResult::resultReady, this, &ProductInWarehouseSectionModel::continueLoadData);
}

void ProductInWarehouseSectionModel::continueLoadData (ModelResult* result)
{
    result->deleteLater();
    if (result->hasError())
    {
        emit notifyWarning("Błąd ładowania danych", result->error().text());
        return;
    }

    QString selectQuery = m_queries->selectQuery(1, result->model()->rowCount());
    QVariantList parameters;
    for (int i = 0; i < result->model()->rowCount(); i++)
        parameters << result->model()->index(i, 2).data();

    ModelResult* newResult = m_databaseClient->selectModel(selectQuery, parameters);
    connect (newResult, &ModelResult::resultReady, this, &ProductInWarehouseSectionModel::finishLoadData);
}

void ProductInWarehouseSectionModel::addData (QVariantList dataList)
{
    QVariantList newDataList;
    for (int i = 0; i < dataList.size(); i++)
        newDataList << m_loadingParameters.at(0) << dataList.at(i);

    ValueResult* result = m_databaseClient->insertData(m_queries->insertQuery(0, dataList.size()), newDataList);
    connect (result, &ValueResult::resultReady, this, &ProductInWarehouseSectionModel::finishAddData);
}

void ProductInWarehouseSectionModel::removeData(QVariantList dataList)
{
    ModelResult* result = m_databaseClient->selectModel(m_queries->selectQuery(2, dataList.size()), dataList);
    connect (result, &ModelResult::resultReady, this, &ProductInWarehouseSectionModel::continueRemoveData);
}

void ProductInWarehouseSectionModel::continueRemoveData (ModelResult* result)
{
    result->deleteLater();
    if (result->hasError())
    {
        emit notifyWarning("Błąd usuwania danych", result->error().text());
        return;
    }

    QVariantList parameters;
    QAbstractTableModel* model = result->model();
    for (int i = 0; i < model->rowCount(); i++)
        parameters << model->index(i, 0).data();

    ValueResult* newResult = m_databaseClient->removeData(m_queries->deleteQuery(0, parameters.size()), parameters);
    connect (newResult, &ValueResult::resultReady, this, &ProductInWarehouseSectionModel::finishRemoveData);
}
